#!/bin/sh /etc/rc.common
#
# Copyright (C) 2017 openwrt-ssr
# Copyright (C) 2017 yushi studio <ywb94@qq.com>
# Copyright (C) 2018 lean <coolsnowwolf@gmail.com>
# Copyright (C) 2020 Mattraks <mattraks@gmail.com>
#
# This is free software, licensed under the GNU General Public License v3.
# See /LICENSE for more information.
#

START=95
STOP=15
SERVICE_DAEMONIZE=1
NAME=shadowsocksr
LOCK_FILE=/var/lock/ssrplus.lock
LOG_FILE=/var/log/ssrplus.log
TMP_PATH=/var/etc/ssrplus
TMP_BIN_PATH=$TMP_PATH/bin
# 设置 DNSMASQ_CONF_DIR 和 TMP_DNSMASQ_PATH
if [ -f /etc/openwrt_release ]; then
    # 获取默认的 DNSMASQ 配置 ID
    DEFAULT_DNSMASQ_CFGID="$(uci -q show "dhcp.@dnsmasq[0]" | awk 'NR==1 {split($0, conf, /[.=]/); print conf[2]}')"
    # 从 conf-dir 行中提取配置目录路径
    if [ -f "/tmp/etc/dnsmasq.conf.$DEFAULT_DNSMASQ_CFGID" ]; then
        DNSMASQ_CONF_DIR="$(awk -F '=' '/^conf-dir=/ {print $2}' "/tmp/etc/dnsmasq.conf.$DEFAULT_DNSMASQ_CFGID")"
    else
        DNSMASQ_CONF_DIR="/tmp/dnsmasq.d"
    fi
    # 设置 TMP_DNSMASQ_PATH，并去除路径末尾的斜杠
    TMP_DNSMASQ_PATH="${DNSMASQ_CONF_DIR%*/}/dnsmasq-ssrplus.d"
fi

chain_config_file=		   #generate shadowtls chain proxy config file
tcp_config_file=
udp_config_file=
shunt_config_file=
local_config_file=
shunt_dns_config_file=
tmp_local_port=

ARG_UDP=

dns_port="5335"            #dns port
china_dns_port="5333"      #china_dns_port
tmp_dns_port="300"         #dns2socks temporary port
tmp_udp_port="301"         #udp temporary port
tmp_udp_local_port="302"   #udp socks temporary port
tmp_shunt_port="303"       #shunt temporary port
tmp_shunt_local_port="304" #shunt socks temporary port
tmp_shunt_dns_port="305"   #shunt dns2socks temporary port
tmp_tcp_local_port="306"   #tcp socks temporary port

server_count=0
redir_tcp=0
redir_udp=0
local_enable=0
kcp_enable_flag=0
pdnsd_enable_flag=0
switch_server=$1
CRON_FILE=/etc/crontabs/root
EXTRA_COMMANDS='reset'
EXTRA_HELP="        reset   Reset to default settings"
#extra_command "reset" "Reset to default settings"
PS="/bin/busybox ps"

uci_get_by_name() {
	local ret=$(uci get $NAME.$1.$2 2>/dev/null)
	echo ${ret:=$3}
}

uci_get_by_type() {
	local ret=$(uci get $NAME.@$1[0].$2 2>/dev/null)
	echo "${ret:=$3}"
}

uci_set_by_name() {
	uci set $NAME.$1.$2=$3 2>/dev/null
	uci commit $NAME
}

uci_set_by_type() {
	uci set $NAME.@$1[0].$2=$3 2>/dev/null
	uci commit $NAME
}

uci_get_by_cfgid() {
	local ret=$(uci show $NAME.@$1[0].$2 | awk -F '.' '{print $2}' 2>/dev/null)
	echo ${ret:=$3}
}

get_host_ip() {
	local host=$(uci_get_by_name $1 server)
	local ip=$host
	if [ -z "$(echo $host | grep -E "([0-9]{1,3}[\.]){3}[0-9]{1,3}")" ]; then
		if [ "$host" == "${host#*:[0-9a-fA-F]}" ]; then
			ip=$(resolveip -4 -t 3 $host | awk 'NR==1{print}')
			[ -z "$ip" ] && ip=$(curl -sSL "http://119.29.29.29/d?dn=$host" | awk -F ';' '{print $1}')
		fi
	fi
	[ -z "$ip" ] || uci_set_by_name $1 ip $ip
	[ -n "$ip" ] || ip="$(uci_get_by_name $1 ip "ERROR")"

	local chinadns="$(uci_get_by_type global chinadns_forward)"
	if [ -n "$chinadns" ] && [ "$ip" != "$host" ]; then
		grep -q "$host" "$TMP_DNSMASQ_PATH/chinadns_fixed_server.conf" 2>"/dev/null" || \
			echo -e "address=/$host/$ip" >> "$TMP_DNSMASQ_PATH/chinadns_fixed_server.conf"
	fi

	echo $ip
}

clean_log() {
	local logsnum=$(cat $LOG_FILE 2>/dev/null | wc -l)
	[ "$logsnum" -gt 1000 ] && {
		echo "$(date "+%Y-%m-%d %H:%M:%S") 日志文件过长，清空处理！" >$LOG_FILE
	}
}

echolog() {
	local d="$(date "+%Y-%m-%d %H:%M:%S")"
	echo -e "$d: $*" >>$LOG_FILE
}

add_cron() {
	touch $CRON_FILE
	sed -i '/ssrplus.log/d' $CRON_FILE
	[ $(uci_get_by_type server_subscribe auto_update 0) -eq 1 ] && echo "$(uci_get_by_type server_subscribe auto_update_min_time) $(uci_get_by_type server_subscribe auto_update_day_time) * * $(uci_get_by_type server_subscribe auto_update_week_time) /usr/share/shadowsocksr/ssrplusupdate.sh >$LOG_FILE" >>$CRON_FILE
	crontab $CRON_FILE
}

del_cron() {
	touch $CRON_FILE
	sed -i '/ssrplus.log/d' $CRON_FILE
	crontab $CRON_FILE
	clean_log
}

set_lock() {
	exec 1000>"$LOCK_FILE"
	flock -xn 1000
}

unset_lock() {
	flock -u 1000
	rm -rf "$LOCK_FILE"
}

unlock() {
	failcount=1
	while [ "$failcount" -le 10 ]; do
		if [ -f "$LOCK_FILE" ]; then
			let "failcount++"
			sleep 1s
			[ "$failcount" -ge 10 ] && unset_lock
		else
			break
		fi
	done
}

_exit() {
	local rc=$1
	unset_lock
	exit ${rc}
}

first_type() {
	type -t -p "/bin/${1}" -p "/usr/bin/${1}" -p "${TMP_BIN_PATH}/${1}" -p "${1}" "$@" | head -n1
}

ln_start_bin() {
	local file_func=${1}
	local ln_name=${2}
	shift 2
	if [ "${file_func%%/*}" != "${file_func}" ]; then
		[ ! -L "${file_func}" ] && {
			ln -s "${file_func}" "${TMP_BIN_PATH}/${ln_name}" >/dev/null 2>&1
			file_func="${TMP_BIN_PATH}/${ln_name}"
		}
		[ -x "${file_func}" ] || echolog "$(readlink ${file_func}) 没有执行权限，无法启动：${file_func} $*"
	fi
	#echo "${file_func} $*" >&2
	[ -x "${file_func}" ] || {
		echolog "找不到 ${file_func}，无法启动..."
		echolog "-----------end------------"
		_exit 2
	}
	ulimit -n 1000000
	${file_func:-echolog "  - ${ln_name}"} "$@" >/dev/null 2>&1 &
}

add_dns_into_ipset() {
	case "$1" in
	gfw) ipset add gfwlist ${2%:*} 2>/dev/null ;;
	oversea) ipset add oversea ${2%:*} 2>/dev/null ;;
	*) ipset add ss_spec_wan_ac ${2%:*} nomatch 2>/dev/null ;;
	esac
}

start_dns() {
	local ssrplus_dns="$(uci_get_by_type global pdnsd_enable 0)"
	local dnsproxy_dnsserver="$(uci_get_by_type global parse_method)"
	if [ -n "$dnsproxy_dnsserver" ] && [ "$dnsproxy_dnsserver" != "parse_file" ]; then
		dnsserver="$(uci_get_by_type global dnsproxy_tunnel_forward 8.8.4.4:53)"
	elif [ -n "$ssrplus_dns" ] && [ "$ssrplus_dns" = "6" ]; then
		dnsserver="$(uci_get_by_type global chinadns_ng_tunnel_forward 8.8.4.4:53)"
	else
		dnsserver="$(uci_get_by_type global tunnel_forward 8.8.4.4:53)"
	fi
	local run_mode="$(uci_get_by_type global run_mode)"

	if [ "$ssrplus_dns" != "0" ]; then
		if command -v iptables-legacy >/dev/null 2>&1; then
			if [ -n "$dnsserver" ]; then
				add_dns_into_ipset $run_mode $dnsserver
			fi
		fi
		case "$ssrplus_dns" in
		1)
			ln_start_bin $(first_type dns2tcp) dns2tcp -L 127.0.0.1#$dns_port -R ${dnsserver/:/#}
			pdnsd_enable_flag=1
			;;
		2)
			ln_start_bin $(first_type microsocks) microsocks -i 127.0.0.1 -p $tmp_dns_port ssrplus-dns
			ln_start_bin $(first_type dns2socks) dns2socks 127.0.0.1:$tmp_dns_port $dnsserver 127.0.0.1:$dns_port -q
			pdnsd_enable_flag=2
			;;
		3)
			ln_start_bin $(first_type microsocks) microsocks -i 127.0.0.1 -p $tmp_dns_port ssrplus-dns
			ln_start_bin $(first_type dns2socks-rust) dns2socks-rust -s socks5://127.0.0.1:$tmp_dns_port -d $dnsserver -l 127.0.0.1:$dns_port -f -c
			echolog "DNS2SOCKS Rust query and cache Started!"
			pdnsd_enable_flag=3
			;;
		4)
			local mosdns_ipv6="$(uci_get_by_type global mosdns_ipv6)"
			local mosdns_dnsserver="$(uci_get_by_type global tunnel_forward_mosdns)"
			output=$(for i in $(echo $mosdns_dnsserver | sed "s/,/ /g"); do
				dnsserver=${i%:*}
				dnsserver=${i##*/}
				if command -v iptables-legacy >/dev/null 2>&1; then
					add_dns_into_ipset $run_mode $dnsserver
				fi
				echo "            - addr: $i"
				echo "              enable_pipeline: true"
			done)

			awk -v line=14 -v text="$output" 'NR == line+1 {print text} 1' /etc/ssrplus/mosdns-config.yaml | sed "s/DNS_PORT/$dns_port/g" | sed "s/\(concurrent:\).*/\1 $(echo "$mosdns_dnsserver" | sed 's/,/ /g' | wc -w)/g"> $TMP_PATH/mosdns-config.yaml
			if [ "$mosdns_ipv6" == "0" ]; then
				sed -i "s/DNS_MODE/main_sequence_with_IPv6/g" $TMP_PATH/mosdns-config.yaml
			else
				sed -i "s/DNS_MODE/main_sequence_disable_IPv6/g" $TMP_PATH/mosdns-config.yaml
			fi
			ln_start_bin $(first_type mosdns) mosdns start -c $TMP_PATH/mosdns-config.yaml
			pdnsd_enable_flag=4
			;;
		5)
			dnsproxy_ipv6="$(uci_get_by_type global dnsproxy_ipv6)"
			if [ "$dnsproxy_ipv6" -eq "1" ]; then
				disabled_ipv6="--ipv6-disabled"
			fi
			if [ "$dnsproxy_dnsserver" != "parse_file" ]; then
				ln_start_bin $(first_type dnsproxy) dnsproxy -l 127.0.0.1 -p $tmp_dns_port  -p $dns_port -u $dnsserver $disabled_ipv6 --cache --cache-min-ttl=3600
			else
				dnsproxy_dnsserver_file="$TMP_PATH/dnsproxy_dns.list"
				cleaned_file="$TMP_PATH/cleaned_dns.list"
				temp_file="$TMP_PATH/temp_dns.list"
				> "$cleaned_file"
				# 清理输入文件并去重
				while IFS= read -r line || [ -n "$line" ]; do
				    line=$(echo "$line" | sed -E 's/^[ \t\r]+//; s/[ \t\r]+$//')
					[ -z "$line" ] && continue
					echo "$line" | grep -qE '^#' && continue
					echo "$line" >> "$cleaned_file"
				done < "/etc/ssrplus/dnsproxy_dns.list"
				# 获取清理后文件的MD5
				cleaned_md5=$(md5sum "$cleaned_file" | awk '{print $1}')
				if [ ! -f "$dnsproxy_dnsserver_file" ]; then
				    cp "$cleaned_file" "$dnsproxy_dnsserver_file"
				else
				    target_md5=$(md5sum "$dnsproxy_dnsserver_file" | awk '{print $1}')
					if [ "$cleaned_md5" != "$target_md5" ]; then
					    > "$temp_file"
					    # 保留目标文件中也存在于清理文件的记录（去重）
					    while IFS= read -r line; do
						    line=$(echo "$line" | sed -E 's/^[ \t\r]+//; s/[ \t\r]+$//')
						    if grep -qixF "$line" "$cleaned_file" && ! grep -qixF "$line" "$temp_file"; then
							    echo "$line" >> "$temp_file"
						    fi
						done < "$dnsproxy_dnsserver_file"
						# 添加清理文件中有但目标文件没有的记录（去重）
						while IFS= read -r line; do
						    line=$(echo "$line" | sed -E 's/^[ \t\r]+//; s/[ \t\r]+$//')
							if ! grep -qixF "$line" "$temp_file"; then
							    echo "$line" >> "$temp_file"
							fi
						done < "$cleaned_file"
						temp_md5=$(md5sum "$temp_file" | awk '{print $1}')
						if [ "$temp_md5" != "$target_md5" ]; then
						    mv "$temp_file" "$dnsproxy_dnsserver_file"
						else
						    rm -f "$temp_file"
						fi
					fi
				fi
				rm -f "$cleaned_file"

				if [ -n "$dnsproxy_dnsserver_file" ] && [ -s "$dnsproxy_dnsserver_file" ]; then
					local upstreams_logic_mode="$(uci_get_by_type global upstreams_logic_mode)"
					ln_start_bin $(first_type dnsproxy) dnsproxy -l 127.0.0.1 -p $tmp_dns_port  -p $dns_port -u $dnsproxy_dnsserver_file $disabled_ipv6 --cache --cache-min-ttl=3600 --upstream-mode=$upstreams_logic_mode
				fi
			fi
			echolog "DNSPROXY query and cache Started!"
			pdnsd_enable_flag=5
			;;
		6)
			local chinadns_ng_proto="$(uci_get_by_type global chinadns_ng_proto)"
			local chinadns_ng_dns=""
			# 遍历每个 DNS 服务器
			IFS=','  # 设置分隔符为逗号
			for chinadns_ng_server in $dnsserver; do
				# 处理单个服务器地址
				local chinadns_ng_ip="${chinadns_ng_server%%:*}"
				local chinadns_ng_port="${chinadns_ng_server##*:}"
				[ "$chinadns_ng_ip" = "$chinadns_ng_port" ] && chinadns_ng_port="53"
				chinadns_ng_tls_port="853"
				# 根据协议类型格式化服务器地址
				case "$chinadns_ng_proto" in
					"none")
            					chinadns_ng_server="${chinadns_ng_ip}#${chinadns_ng_port}"
            					;;
					"tls")
            					chinadns_ng_server="${chinadns_ng_proto}://${chinadns_ng_ip}#${chinadns_ng_tls_port}"
            					;;
					*)
            					chinadns_ng_server="${chinadns_ng_proto}://${chinadns_ng_ip}#${chinadns_ng_port}"
            					;;
				esac
				# 添加到参数列表
				chinadns_ng_dns="${chinadns_ng_dns} -t ${chinadns_ng_server}"
			done
			unset IFS  # 恢复默认分隔符
			dnsserver="$chinadns_ng_dns"
			ln_start_bin $(first_type chinadns-ng) chinadns-ng -b 127.0.0.1 -l $tmp_dns_port -l $dns_port -p 3 -d gfw $dnsserver -N --filter-qtype 64,65 -f -r --cache 4096 --cache-stale 86400 --cache-refresh 20
			echolog "ChinaDNS-NG query and cache Started!"
			pdnsd_enable_flag=6
			;;
		esac

		if [ "$run_mode" = "router" ]; then
			local chinadns="$(uci_get_by_type global chinadns_forward)"
			if [ -n "$chinadns" ]; then
				local wandns="$(ifstatus wan | jsonfilter -e '@["dns-server"][0]' || echo "119.29.29.29")"
				case "$chinadns" in
				"wan") chinadns="$wandns" ;;
				"wan_114") chinadns="$wandns,114.114.114.114" ;;
				esac

				ln_start_bin $(first_type chinadns-ng) chinadns-ng -l $china_dns_port -4 china -p 3 -c ${chinadns/:/#} -t 127.0.0.1#$dns_port -N -f -r

				cat <<-EOF >> "$TMP_DNSMASQ_PATH/chinadns_fixed_server.conf"
					no-poll
					no-resolv
					server=127.0.0.1#$china_dns_port
				EOF
			fi
		fi
	fi

	if [ "$(uci_get_by_type global apple_optimization 1)" == "1" ]; then
		local new_appledns="$(uci_get_by_type global apple_dns)"
		if [ -n "$new_appledns" ]; then		
			sed -i 's/[[:space:]]//g' /etc/ssrplus/applechina.conf #去除所有空白字符
			local old_appledns=$(grep -oE '[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+' /etc/ssrplus/applechina.conf | sort -u)
			if [ -n "$old_appledns" ] && [ "$old_appledns" != "$new_appledns" ]; then
				sed -i "s,$(printf '%s' "$old_appledns"),$(printf '%s' "$new_appledns"),g" /etc/ssrplus/applechina.conf
			fi
		fi
		echolog "Apple 域名中国大陆 CDN 的 优化规则正在加载。"
		cp -f /etc/ssrplus/applechina.conf $TMP_DNSMASQ_PATH/
		echolog "Apple 域名中国大陆 CDN 的 优化规则加载完毕。"
	fi
}

gen_service_file() { #1-server.type 2-cfgname 3-file_path
	local fastopen
	if [ $(uci_get_by_name $2 fast_open) == "1" ]; then
		fastopen="true"
	else
		fastopen="false"
	fi
	case $1 in
		ssr)
		cat <<-EOF >$3
			{
				"server": "0.0.0.0",
				"server_ipv6": "::",
				"server_port": $(uci_get_by_name $2 server_port),
				"mode": "tcp_and_udp",
				"password": "$(uci_get_by_name $2 password)",
				"timeout": $(uci_get_by_name $2 timeout 60),
				"method": "$(uci_get_by_name $2 encrypt_method)",
				"protocol": "$(uci_get_by_name $2 protocol)",
				"protocol_param": "$(uci_get_by_name $2 protocol_param)",
				"obfs": "$(uci_get_by_name $2 obfs)",
				"obfs_param": "$(uci_get_by_name $2 obfs_param)",
				"fast_open": $fastopen
			}
			EOF
		;;
		ss)
			cat <<-EOF >$3
				{
					"server": "0.0.0.0",
					"server_ipv6": "::",
					"server_port": $(uci_get_by_name $2 server_port),
					"mode": "tcp_and_udp",
					"password": "$(uci_get_by_name $2 password)",
					"timeout": $(uci_get_by_name $2 timeout 60),
					"method": "$(uci_get_by_name $2 encrypt_method_ss)",
					"protocol": "socks",
					"fast_open": $fastopen
				}
			EOF
		;;
	esac
}

get_name() {
	case "$1" in
	ss) echo "ShadowSocks" ;;
	ssr) echo "ShadowsocksR" ;;
	esac
}

gen_config_file() { #server1 type2 code3 local_port4 socks_port5 chain6 threads5
	case "$3" in
	1)
		config_file=$tcp_config_file
		chain_config_file=$(echo ${config_file}|sed 's/ssrplus\//ssrplus\/chain-/')
		;;
	2)
		config_file=$udp_config_file
		chain_config_file=$(echo ${config_file}|sed 's/ssrplus\//ssrplus\/chain-/')
		;;
	3)
		if [ -n "$tmp_local_port" ]; then
			local tmp_port=$tmp_local_port
		else
			local tmp_port=$tmp_shunt_local_port
		fi
		config_file=$shunt_config_file
		chain_config_file=$(echo ${config_file}|sed 's/ssrplus\//ssrplus\/chain-/')
		;;
	4)
		local ss_protocol="socks"
		config_file=$local_config_file
		chain_config_file=$(echo ${config_file}|sed 's/ssrplus\//ssrplus\/chain-/')
		;;
	esac
	case "$2" in
	ss | ssr)
		lua /usr/share/shadowsocksr/gen_config.lua $1 $mode $4 ${ss_protocol:-redir} >$config_file
		if [ "$3" == "3" ]; then
			lua /usr/share/shadowsocksr/gen_config.lua $1 $mode $tmp_port socks >$shunt_dns_config_file
		fi
		;;
	v2ray)
		lua /usr/share/shadowsocksr/gen_config.lua $1 $mode $4 $5 >$config_file
		;;
	trojan)
		case "$3" in
		1)
			lua /usr/share/shadowsocksr/gen_config.lua $1 nat $4 >$config_file
			;;
		2)
			lua /usr/share/shadowsocksr/gen_config.lua $1 client $4 >$config_file
			;;
		3)
			lua /usr/share/shadowsocksr/gen_config.lua $1 nat $4 >$config_file
			lua /usr/share/shadowsocksr/gen_config.lua $1 client $tmp_port >$shunt_dns_config_file
			;;
		4)
			lua /usr/share/shadowsocksr/gen_config.lua $1 client $4 >$config_file
			;;
		esac
		;;
	naiveproxy)
		case "$3" in
		1)
			lua /usr/share/shadowsocksr/gen_config.lua $1 redir $4 >$config_file
			;;
		3)
			lua /usr/share/shadowsocksr/gen_config.lua $1 redir $4 >$config_file
			lua /usr/share/shadowsocksr/gen_config.lua $1 socks $tmp_port >$shunt_dns_config_file
			;;
		4)
			lua /usr/share/shadowsocksr/gen_config.lua $1 socks $4 >$config_file
			;;
		esac
		;;
	hysteria2)
		lua /usr/share/shadowsocksr/gen_config.lua $1 $mode $4 $5 >$config_file
		;;
	tuic)
		case "$3" in
		1|2|4)
			lua /usr/share/shadowsocksr/gen_config.lua $1 $mode $4 >$config_file
			;;
		3)
			[ -z "$6" ] && lua /usr/share/shadowsocksr/gen_config.lua $1 $mode $4 >$shunt_dns_config_file || lua /usr/share/shadowsocksr/gen_config.lua $1 $mode $4 >$config_file
			;;
		esac
		;;
	shadowtls)
		case "$3" in
		1|2|4)
			[ -z "$6" ] && lua /usr/share/shadowsocksr/gen_config.lua $1 $type $4 >$chain_config_file || lua /usr/share/shadowsocksr/gen_config.lua $1 $mode $4 $5 $6 >$config_file
			;;
		3)
			lua /usr/share/shadowsocksr/gen_config.lua $1 $type $4 >$chain_config_file
			lua /usr/share/shadowsocksr/gen_config.lua $1 $mode $4 $5 $6 >$config_file
			;;
		esac
		;;
	socks5)
		/usr/share/shadowsocksr/genred2config.sh $config_file $2 $mode $4 \
			"$(uci_get_by_name $1 server)" \
			"$(uci_get_by_name $1 server_port)" \
			"$(uci_get_by_name $1 auth_enable 0)" \
			"$(uci_get_by_name $1 username)" \
			"$(uci_get_by_name $1 password)"
		;;
	tun)
		/usr/share/shadowsocksr/genred2config.sh $config_file $2 $(uci_get_by_name $1 iface "br-lan") $4
		;;
	esac
	sed -i 's/\\//g' $TMP_PATH/*-ssr-*.json #>/dev/null > 2>&1
}

start_udp() {
	local type=$(uci_get_by_name $UDP_RELAY_SERVER type)
	local has_ss_type=$(uci_get_by_type server_subscribe ss_type)
	redir_udp=1
	case "$type" in
	ss | ssr)
		gen_config_file $UDP_RELAY_SERVER $type 2 $tmp_udp_port
		if [ "$has_ss_type" = "ss-libev" -o "$type" = "ssr" ]; then
			ss_program="$(first_type ${type}-redir)"
		elif [ "$has_ss_type" = "ss-rust" ]; then
			ss_program="$(first_type ${type}local)"
		fi
		echolog "$(get_name $type) program is: $ss_program"
		# 获取当前软链接指向的执行文件路径
		old_ss_program=$(readlink -f "$TMP_PATH/bin/${type}-redir" 2>/dev/null)
		# **当新旧执行文件路径不同时，删除旧链接**
		if [ "$old_ss_program" != "$ss_program" ]; then
			rm -rf "$TMP_PATH/bin/${type}-redir"
		fi
		ln_start_bin $ss_program ${type}-redir -c $udp_config_file
		echolog "UDP TPROXY Relay:$(get_name $type) Started!"
		;;
	v2ray)
		gen_config_file $UDP_RELAY_SERVER $type 2 $tmp_udp_port
		ln_start_bin $(first_type xray v2ray) v2ray run -c $udp_config_file
		echolog "UDP TPROXY Relay:$($(first_type "xray" "v2ray") version | head -1) Started!"
		;;
	trojan) #client
		gen_config_file $UDP_RELAY_SERVER $type 2 $tmp_udp_local_port
		ln_start_bin $(first_type trojan) $type --config $udp_config_file
		ln_start_bin $(first_type ipt2socks) ipt2socks -U -b 0.0.0.0 -4 -s 127.0.0.1 -p $tmp_udp_local_port -l $tmp_udp_port
		echolog "UDP TPROXY Relay:$($(first_type trojan) --version 2>&1 | head -1) Started!"
		;;
	naiveproxy)
		echolog "NaïveProxy UDP TPROXY Relay not supported!"
		redir_udp=0
		ARG_UDP=""
		;;
	hysteria2)
		gen_config_file $UDP_RELAY_SERVER $type 2 $tmp_udp_port
		ln_start_bin $(first_type hysteria) hysteria client --config $udp_config_file
		echolog "UDP TPROXY Relay:$($(first_type "hysteria") version | grep Version | awk '{print "Hysteria2: " $2}') Started!"
		;;
	tuic)
		# FIXME: ipt2socks cannot handle udp reply from tuic
		# 20230726 uncomment following 4 lines
		gen_config_file $UDP_RELAY_SERVER $type 2 $tmp_udp_local_port
		ln_start_bin $(first_type tuic-client) tuic-client --config $udp_config_file
		ln_start_bin $(first_type ipt2socks) ipt2socks -U -b 0.0.0.0 -4 -s 127.0.0.1 -p $tmp_udp_local_port -l $tmp_udp_port
		echolog "UDP TPROXY Relay:tuic-client $($(first_type tuic-client) --version) Started!"
		echolog "TUIC UDP TPROXY Relay not supported!"
		#redir_udp=0
		#ARG_UDP=""
		;;
	shadowtls)
		gen_config_file $UDP_RELAY_SERVER $type 2 ${tmp_udp_local_port}
		gen_config_file $UDP_RELAY_SERVER $type 2 ${tmp_udp_local_port} 0 chain
		ln_start_bin $(first_type shadow-tls) shadow-tls config --config $chain_config_file
		local chain_type=$(uci_get_by_name $UDP_RELAY_SERVER chain_type)
		case ${chain_type} in
		vmess)
			ln_start_bin $(first_type xray v2ray) v2ray run -c $udp_config_file
			echolog "UDP TPROXY Relay:shadow-tls chain-to $($(first_type xray) --version) Started!"
			;;
		sslocal)
			ln_start_bin $(first_type sslocal) sslocal -c $udp_config_file
			echolog "UDP TPROXY Relay:shadow-tls chain-to $($(first_type sslocal) --version) Started!"
			;;
		esac
		;;
	socks5)
		# if [ "$(uci_get_by_name $UDP_RELAY_SERVER auth_enable 0)" == "1" ]; then
		# 	local auth="-a $(uci_get_by_name $UDP_RELAY_SERVER username) -k $(uci_get_by_name $UDP_RELAY_SERVER password)"
		# fi
		# ln_start_bin $(first_type ipt2socks) ipt2socks $udp_config_file -U -4 -s $(uci_get_by_name $UDP_RELAY_SERVER server) -p $(uci_get_by_name $UDP_RELAY_SERVER server_port) -l $tmp_udp_port $auth
		gen_config_file $UDP_RELAY_SERVER $type 2 $tmp_udp_port
		ln_start_bin $(first_type redsocks2) redsocks2 -c $udp_config_file
		echolog "UDP TPROXY Relay:Socks5 REDIRECT/TPROXY Started!"
		;;
	tun)
		echolog "Network Tunnel UDP TPROXY Relay not supported!"
		redir_udp=0
		ARG_UDP=""
		;;
	esac
}

shunt_dns_command() {
	local shunt_dns_mode="$(uci_get_by_type global shunt_dns_mode)"
	local shunt_dnsproxy_dnsserver="$(uci_get_by_type global shunt_parse_method)"
	if [ -n "$shunt_dnsproxy_dnsserver" ] && [ "$shunt_dnsproxy_dnsserver" != "parse_file" ]; then
		shunt_dnsserver="$(uci_get_by_type global dnsproxy_shunt_forward 8.8.4.4:53)"
	elif [ -n "shunt_dns_mode" ] && [ "$shunt_dns_mode" = "5" ]; then
		shunt_dnsserver="$(uci_get_by_type global chinadns_ng_shunt_dnsserver 8.8.4.4:53)"
	else
		shunt_dnsserver="$(uci_get_by_type global shunt_dnsserver 8.8.4.4:53)"
	fi
	local tmp_port=$1
	case "$shunt_dns_mode" in
	1)
		ln_start_bin $(first_type dns2socks) dns2socks 127.0.0.1:$tmp_port $shunt_dnsserver 127.0.0.1:$tmp_shunt_dns_port -q
		;;
	2)
		ln_start_bin $(first_type dns2socks-rust) dns2socks-rust -s socks5://127.0.0.1:$tmp_port -d $shunt_dnsserver -l 127.0.0.1:$tmp_shunt_dns_port -f -c
		echolog "DNS2SOCKS Rust Shunt query Started!"
		;;
	3)
		local shunt_mosdns_ipv6="$(uci_get_by_type global shunt_mosdns_ipv6)"
		local shunt_mosdns_dnsserver="$(uci_get_by_type global shunt_mosdns_dnsserver)"
		output=$(for i in $(echo $shunt_mosdns_dnsserver | sed "s/,/ /g"); do
			echo "            - addr: $i"
			echo "              socks5: \"127.0.0.1:$tmp_port\""
			echo "              enable_pipeline: true"
		done)
		awk -v line=14 -v text="$output" 'NR == line+1 {print text} 1' /etc/ssrplus/mosdns-config.yaml | sed "s/DNS_PORT/$tmp_shunt_dns_port/g" | sed "s/\(concurrent:\).*/\1 $(echo "$mosdns_dnsserver" | sed 's/,/ /g' | wc -w)/g" > $TMP_PATH/mosdns-config-shunt.yaml

		if [ "$shunt_mosdns_ipv6" == "0" ]; then
			sed -i "s/DNS_MODE/main_sequence_with_IPv6/g" $TMP_PATH/mosdns-config-shunt.yaml
		else
			sed -i "s/DNS_MODE/main_sequence_disable_IPv6/g" $TMP_PATH/mosdns-config-shunt.yaml
		fi
		ln_start_bin $(first_type mosdns) mosdns start -c $TMP_PATH/mosdns-config-shunt.yaml
		;;
	4)
		shunt_dnsproxy_ipv6="$(uci_get_by_type global shunt_dnsproxy_ipv6)"
		if [ "$shunt_dnsproxy_ipv6" -eq "1" ]; then
			shunt_disabled_ipv6="--ipv6-disabled"
		fi
		if [ "$shunt_dnsproxy_dnsserver" != "parse_file" ]; then
			ln_start_bin $(first_type dnsproxy) dnsproxy -l 127.0.0.1 -p $tmp_port -p $tmp_shunt_dns_port -u $shunt_dnsserver $shunt_disabled_ipv6 --cache --cache-min-ttl=3600
		else
			shunt_dnsproxy_dnsserver_file="$TMP_PATH/dnsproxy_dns.list"
			cleaned_file="$TMP_PATH/cleaned_dns_servers.list"
			temp_file="$TMP_PATH/temp_dns_servers.list"
			> "$cleaned_file"
			# 清理输入文件并去重
			while IFS= read -r line || [ -n "$line" ]; do
			    line=$(echo "$line" | sed -E 's/^[ \t\r]+//; s/[ \t\r]+$//')
				[ -z "$line" ] && continue
				echo "$line" | grep -qE '^#' && continue
				echo "$line" >> "$cleaned_file"
			done < "/etc/ssrplus/dnsproxy_dns.list"
			# 获取清理后文件的MD5
			cleaned_md5=$(md5sum "$cleaned_file" | awk '{print $1}')
			if [ ! -f "$shunt_dnsproxy_dnsserver_file" ]; then
			    cp "$cleaned_file" "$shunt_dnsproxy_dnsserver_file"
			else
			    target_md5=$(md5sum "$shunt_dnsproxy_dnsserver_file" | awk '{print $1}')
				if [ "$cleaned_md5" != "$target_md5" ]; then
				    > "$temp_file"
					# 保留目标文件中也存在于清理文件的记录（去重）
					while IFS= read -r line; do
					    line=$(echo "$line" | sed -E 's/^[ \t\r]+//; s/[ \t\r]+$//')
						if grep -qixF "$line" "$cleaned_file" && ! grep -qixF "$line" "$temp_file"; then
						    echo "$line" >> "$temp_file"
						fi
					done < "$shunt_dnsproxy_dnsserver_file"
					# 添加清理文件中有但目标文件没有的记录（去重）
					while IFS= read -r line; do
					    line=$(echo "$line" | sed -E 's/^[ \t\r]+//; s/[ \t\r]+$//')
						if ! grep -qixF "$line" "$temp_file"; then
						    echo "$line" >> "$temp_file"
						fi
					done < "$cleaned_file"
					temp_md5=$(md5sum "$temp_file" | awk '{print $1}')
					if [ "$temp_md5" != "$target_md5" ]; then
					    mv "$temp_file" "$shunt_dnsproxy_dnsserver_file"
					else
						rm -f "$temp_file"
					fi
				fi
			fi
			rm -f "$cleaned_file"
			
			if [ -n "$shunt_dnsproxy_dnsserver_file" ] && [ -s "$shunt_dnsproxy_dnsserver_file" ]; then
				local shunt_upstreams_logic_mode="$(uci_get_by_type global shunt_upstreams_logic_mode)"
				ln_start_bin $(first_type dnsproxy) dnsproxy -l 127.0.0.1 -p $tmp_port -p $tmp_shunt_dns_port -u $shunt_dnsproxy_dnsserver_file $shunt_disabled_ipv6 --cache --cache-min-ttl=3600 --upstream-mode=$shunt_upstreams_logic_mode
			fi
		fi
		echolog "DNSPROXY shunt query and cache Started!"
		;;
	5)
		local chinadns_ng_shunt_proto="$(uci_get_by_type global chinadns_ng_shunt_proto)"
		local chinadns_ng_shunt_dns=""
		# 遍历每个 DNS 服务器
		IFS=','  # 设置分隔符为逗号
		for chinadns_ng_shunt_server in $shunt_dnsserver; do
			# 处理单个服务器地址
			local chinadns_ng_shunt_ip="${chinadns_ng_shunt_server%%:*}"
			local chinadns_ng_shunt_port="${chinadns_ng_shunt_server##*:}"
			[ "$chinadns_ng_shunt_ip" = "$chinadns_ng_shunt_port" ] && chinadns_ng_shunt_port="53"
			chinadns_ng_shunt_tls_port="853"
			# 根据协议类型格式化服务器地址
			case "$chinadns_ng_shunt_proto" in
				"none")
            				chinadns_ng_shunt_server="${chinadns_ng_shunt_ip}#${chinadns_ng_shunt_port}"
            				;;
				"tls")
            				chinadns_ng_shunt_server="${chinadns_ng_shunt_proto}://${chinadns_ng_shunt_ip}#${chinadns_ng_shunt_tls_port}"
            				;;
				*)
            				chinadns_ng_shunt_server="${chinadns_ng_shunt_proto}://${chinadns_ng_shunt_ip}#${chinadns_ng_shunt_port}"
            				;;
			esac
			# 添加到参数列表
			chinadns_ng_shunt_dns="${chinadns_ng_shunt_dns} -t ${chinadns_ng_shunt_server}"
		done
		unset IFS  # 恢复默认分隔符
		shunt_dnsserver="$chinadns_ng_shunt_dns"
		# 启动 chinadns-ng
		ln_start_bin $(first_type chinadns-ng) chinadns-ng -b 127.0.0.1 -l $tmp_port -l $tmp_shunt_dns_port -p 3 -d gfw $shunt_dnsserver -N --filter-qtype 64,65 -f -r --cache 4096 --cache-stale 86400 --cache-refresh 20
		echolog "ChinaDNS-NG shunt query and cache Started!"
		;;
	esac
}

shunt_dns_config_file_port() {
    if [ "$LOCAL_SERVER" == "$SHUNT_SERVER" ]; then
        # NetFlix 和 全局socks 节点相同
        if [ "$(uci_get_by_type socks5_proxy socks5_auth nil)" != "noauth" ]; then
            # 全局socks 有密码，NetFlix 不能使用 auth 验证，需更换为新端口并使用无密码的 socks 配置用于分流
            # 新增NetFlix dns 使用端口
            local port=$tmp_shunt_local_port
            jq --arg port "$port" '.inbounds |= .[0:1] + [{"protocol":"socks","port":($port | tonumber),"settings":{"udp":true,"auth":"noauth"}}] + .[1:]' "$shunt_config_file" > "$shunt_config_file.tmp" && mv "$shunt_config_file.tmp" $shunt_config_file
            echo $port  # 返回端口号
            return 0  # 成功返回
        else
            sed -i -e '/"mixed"/d' $shunt_config_file
        fi
    else
        # NetFlix 和 全局 socks 节点不相同
        if [ "$(uci_get_by_type socks5_proxy socks5_auth nil)" != "noauth" ]; then
            # 全局socks 有密码，NetFlix不能使用auth验证，需设置为无密码的socks配置用于分流
            # 删除 NetFlix dns 端口密码验证
            sed -i \
                   -e '/"mixed"/d' \
                   -e 's/"auth"\s*:\s*"password"/\"auth\": \"noauth\"/g' \
                   -e '/"accounts": \[/,/\]/d' $shunt_config_file
        else
            sed -i -e '/"mixed"/d' $shunt_config_file
        fi
    fi
    # 使用传入的端口
    echo $1  # 返回传入的端口号
    return 0  # 成功返回
}

start_shunt() {
	local type=$(uci_get_by_name $SHUNT_SERVER type)
	local has_ss_type=$(uci_get_by_type server_subscribe ss_type)
	case "$type" in
	ss | ssr)
		gen_config_file $SHUNT_SERVER $type 3 $tmp_shunt_port
		if [ "$has_ss_type" = "ss-libev" -o "$type" = "ssr" ]; then
			ss_program="$(first_type ${type}-redir)"
		elif [ "$has_ss_type" = "ss-rust" ]; then
			ss_program="$(first_type ${type}local)"
		fi
		echolog "$(get_name $type) program is: $ss_program"
		# 获取当前软链接指向的执行文件路径
		old_ss_program=$(readlink -f "$TMP_PATH/bin/${type}-redir" 2>/dev/null)
		# **当新旧执行文件路径不同时，删除旧链接**
		if [ "$old_ss_program" != "$ss_program" ]; then
			rm -rf "$TMP_PATH/bin/${type}-redir"
		fi
		ln_start_bin $ss_program ${type}-redir -c $shunt_config_file
		if [ -n "$tmp_local_port" ]; then
			local tmp_port=$tmp_local_port
		else
			local tmp_port=$tmp_shunt_local_port
			if [ "$has_ss_type" = "ss-libev" -o "$type" = "ssr" ]; then
				dns_ss_program="$(first_type ${type}-local)"
			elif [ "$has_ss_type" = "ss-rust" ]; then
				dns_ss_program="$(first_type ${type}local)"
			fi
			# 获取当前软链接指向的执行文件路径
			old_dns_ss_program=$(readlink -f "$TMP_PATH/bin/${type}-local" 2>/dev/null)
			if [ "$old_dns_ss_program" != "$dns_ss_program" ]; then
				rm -rf "$TMP_PATH/bin/${type}-local"
			fi
			ln_start_bin $dns_ss_program ${type}-local -c $shunt_dns_config_file
		fi
		shunt_dns_command $tmp_port
		echolog "shunt:$(get_name $type) Started!"
		;;
	v2ray)
		local tmp_port=${tmp_local_port:-$tmp_shunt_local_port}
		gen_config_file $SHUNT_SERVER $type 3 $tmp_shunt_port $tmp_port
		# 处理配置文件中的 NetFlix 端口
		tmp_port=$(shunt_dns_config_file_port $tmp_port)
		ln_start_bin $(first_type xray v2ray) v2ray run -c $shunt_config_file
		shunt_dns_command $tmp_port
		echolog "shunt:$($(first_type xray v2ray) version | head -1) Started!"
		;;
	trojan)
		gen_config_file $SHUNT_SERVER $type 3 $tmp_shunt_port
		ln_start_bin $(first_type trojan) $type --config $shunt_config_file
		if [ -n "$tmp_local_port" ]; then
			local tmp_port=$tmp_local_port
		else
			local tmp_port=$tmp_shunt_local_port
			ln_start_bin $(first_type trojan) $type --config $shunt_dns_config_file
		fi
		shunt_dns_command $tmp_port
		echolog "shunt:$($(first_type trojan) --version 2>&1 | head -1) Started!"
		;;
	naiveproxy)
		gen_config_file $SHUNT_SERVER $type 3 $tmp_shunt_port
		ln_start_bin $(first_type naive) naive --config $shunt_config_file
		if [ -n "$tmp_local_port" ]; then
			local tmp_port=$tmp_local_port
		else
			local tmp_port=$tmp_shunt_local_port
			ln_start_bin $(first_type naive) naive --config $shunt_dns_config_file
		fi
		shunt_dns_command $tmp_port
		echolog "shunt:$($(first_type "naive") --version 2>&1 | head -1) Started!"
		redir_udp=0
		;;
	hysteria2)
		if [ -n "$tmp_local_port" ]; then
			local tmp_port=$tmp_local_port
			gen_config_file $SHUNT_SERVER $type 3 $tmp_shunt_port
		else
			local tmp_port=$tmp_shunt_local_port
			gen_config_file $SHUNT_SERVER $type 3 $tmp_shunt_port $tmp_port
		fi
		ln_start_bin $(first_type hysteria) hysteria client --config $shunt_config_file
		shunt_dns_command $tmp_port
		echolog "shunt:$($(first_type hysteria) version | grep Version | awk '{print "Hysteria2: " $2}') Started!"
		;;
	tuic)
		local chain_shunt_port="30${tmp_shunt_port}"
		gen_config_file $SHUNT_SERVER $type 3 $chain_shunt_port 0 chain #make a tuic socks:30303, make a ipt2socks redir:303
		ln_start_bin $(first_type tuic-client) tuic-client --config $shunt_config_file
		ln_start_bin $(first_type ipt2socks) ipt2socks -R -b 0.0.0.0 -4 -s 127.0.0.1 -p $chain_shunt_port -l $tmp_shunt_port

		[ -n "$tmp_local_port" ] && tmp_port=$tmp_local_port || tmp_port=$tmp_shunt_local_port
		gen_config_file $SHUNT_SERVER $type 3 $tmp_port		# make a tuic socks :304
		ln_start_bin $(first_type tuic-client) tuic-client --config $shunt_dns_config_file
		shunt_dns_command $tmp_port
		echolog "Netflix Separated Shunt Server:tuic-client $($(first_type tuic-client) --version) Started!"
		# FIXME: ipt2socks cannot handle udp reply from tuic
		#redir_udp=0
		;;
	shadowtls)
		[ -n "$tmp_local_port" ] && tmp_port=$tmp_local_port || tmp_port=$tmp_shunt_local_port
		gen_config_file $SHUNT_SERVER $type 3 "10${tmp_shunt_port}" $tmp_port chain/$tmp_shunt_port #make a redir:303 and a socks:304
		#echo "debug \$tmp_port=$tmp_port, \$tmp_shunt_port=${tmp_shunt_port},  \$tmp_shunt_local_port=$tmp_shunt_local_port"
		ln_start_bin $(first_type shadow-tls) shadow-tls config --config $chain_config_file
		shunt_dns_command $tmp_port
		local chain_type=$(uci_get_by_name $SHUNT_SERVER chain_type)
		case ${chain_type} in
		vmess)
			ln_start_bin $(first_type xray v2ray) v2ray run -c $shunt_config_file
			echolog "Netflix Separated Shunt Server:shadow-tls chain-to$($(first_type xray) --version) Started!"
			;;
		sslocal)
			ln_start_bin $(first_type sslocal) sslocal -c $shunt_config_file
			echolog "Netflix Separated Shunt Server:shadow-tls chain-to$($(first_type sslocal) --version) Started!"
			;;
		esac
		;;
	# socks5)
	# 	if [ "$(uci_get_by_name $SHUNT_SERVER auth_enable 0)" == "1" ]; then
	# 		local auth="-a $(uci_get_by_name $SHUNT_SERVER username) -k $(uci_get_by_name $SHUNT_SERVER password)"
	# 	fi
	# 	ln_start_bin $(first_type ipt2socks) ipt2socks $shunt_config_file -R -4 -s $(uci_get_by_name $SHUNT_SERVER server) -p $(uci_get_by_name $SHUNT_SERVER server_port) -l $tmp_shunt_port $auth
	# 	#gen_config_file $SHUNT_SERVER $type 3 $tmp_shunt_port
	# 	#ln_start_bin $(first_type redsocks2) redsocks2 -c $shunt_config_file
	# 	if [ -n "$tmp_local_port" ]; then
	# 		local tmp_port=$tmp_local_port
	# 	else
	# 		local tmp_port=$tmp_shunt_local_port
	# 		ln_start_bin $(first_type microsocks) microsocks -i 127.0.0.1 -p $tmp_port shunt-dns-ssr-plus
	# 	fi
	# 	shunt_dns_command $tmp_port
	# 	echolog "shunt:$type REDIRECT/TPROXY Started!"
	# 	;;
	*)
		gen_config_file $SHUNT_SERVER $type 3 $tmp_shunt_port
		ln_start_bin $(first_type redsocks2) redsocks2 -c $shunt_config_file
		if [ -n "$tmp_local_port" ]; then
			local tmp_port=$tmp_local_port
		else
			local tmp_port=$tmp_shunt_local_port
			ln_start_bin $(first_type microsocks) microsocks -i 127.0.0.1 -p $tmp_port shunt-dns-ssr-plus
		fi
		shunt_dns_command $tmp_port
		echolog "shunt:$type REDIRECT/TPROXY Started!"
		;;
	esac
	return 0
}

start_local() {
	[ "$LOCAL_SERVER" = "nil" ] && return 1
	local local_port=$(uci_get_by_type socks5_proxy local_port)
	[ "$LOCAL_SERVER" == "$SHUNT_SERVER" ] && tmp_local_port=$local_port
	local type=$(uci_get_by_name $LOCAL_SERVER type)
	local has_ss_type=$(uci_get_by_type server_subscribe ss_type)
	case "$type" in
	ss | ssr)
		gen_config_file $LOCAL_SERVER $type 4 $local_port
		if [ "$has_ss_type" = "ss-libev" -o "$type" = "ssr" ]; then
			ss_program="$(first_type ${type}-local)"
		elif [ "$has_ss_type" = "ss-rust" ]; then
			ss_program="$(first_type ${type}local)"
		fi
		echolog "$(get_name $type) program is: $ss_program"
		# 获取当前软链接指向的执行文件路径
		old_ss_program=$(readlink -f "$TMP_PATH/bin/${type}-local" 2>/dev/null)
		# **当 新旧执行文件路径不同时，删除旧链接**
		if [ "$old_ss_program" != "$ss_program" ]; then
			rm -rf "$TMP_PATH/bin/${type}-local"
		fi
		ln_start_bin $ss_program ${type}-local -c $local_config_file
		echolog "Global_Socks5:$(get_name $type) Started!"
		;;
	v2ray)
		if [ "$_local" == "2" ]; then
			gen_config_file $LOCAL_SERVER $type 4 0 $local_port
			ln_start_bin $(first_type xray v2ray) v2ray run -c $local_config_file
		fi
		echolog "Global_Socks5:$($(first_type "xray" "v2ray") version | head -1) Started!"
		;;
	trojan) #client
		gen_config_file $LOCAL_SERVER $type 4 $local_port
		ln_start_bin $(first_type trojan) $type --config $local_config_file
		echolog "Global_Socks5:$($(first_type trojan) --version 2>&1 | head -1) Started!"
		;;
	naiveproxy)
		gen_config_file $LOCAL_SERVER $type 4 $local_port
		ln_start_bin $(first_type naive) naive --config $local_config_file
		echolog "Global_Socks5:$($(first_type naive) --version | head -1) Started!"
		;;
	hysteria2)
		if [ "$_local" == "2" ]; then
			gen_config_file $LOCAL_SERVER $type 4 0 $local_port
			ln_start_bin $(first_type hysteria) hysteria client --config $local_config_file
			echolog "Global_Socks5:$($(first_type hysteria) version | grep Version | awk '{print "Hysteria2: " $2}') Started!"
		fi
		;;
	tuic)
		if [ "$_local" == "2" ]; then
			gen_config_file $LOCAL_SERVER $type 4 $local_port
			ln_start_bin $(first_type tuic-client) tuic-client --config $local_config_file
			echolog "Global Socks5:tuic-client $($(first_type tuic-client) --version) Started!"
		fi
		;;
	shadowtls)
		#respective config for global socks and main node
		if [ "$_local" == "2" ]; then
			gen_config_file $LOCAL_SERVER $type 4 "10${tmp_tcp_local_port}"
			gen_config_file $LOCAL_SERVER $type 4 0 $local_port chain/"10${tmp_tcp_local_port}"
			ln_start_bin $(first_type shadow-tls) shadow-tls config --config $chain_local_config_file
			local chain_type=$(uci_get_by_name $LOCAL_SERVER chain_type)
			case ${chain_type} in
			vmess)
				ln_start_bin $(first_type xray v2ray) v2ray run -c $local_config_file
				echolog "Global Socks5 Proxy:shadow-tls chain-to$($(first_type xray) --version) Started!"
				;;
			sslocal)
				ln_start_bin $(first_type sslocal) sslocal -c $local_config_file
				echolog "Global Socks5 Proxy:shadow-tls chain-to$($(first_type sslocal) --version) Started!"
				;;
			esac
		fi
		;;
	*)
		[ -e /proc/sys/net/ipv6 ] && local listenip='-i ::'
		ln_start_bin $(first_type microsocks) microsocks $listenip -p $local_port tcp-udp-ssr-local
		echolog "Global_Socks5:$type Started!"
		;;
	esac
	local_enable=1
	return 0
}

Start_Run() {
	if [ "$(uci_get_by_type global threads 0)" == "0" ]; then
		local threads=$(cat /proc/cpuinfo | grep 'processor' | wc -l)
	else
		local threads=$(uci_get_by_type global threads)
	fi
	if [ "$(uci_get_by_name $GLOBAL_SERVER kcp_enable 0)" == "1" ]; then
		[ ! -f "/usr/bin/kcptun-client" ] && return 1
		local kcp_str=$(/usr/bin/kcptun-client -v | grep kcptun | wc -l)
		[ "0" == "$kcp_str" ] && return 1
		local kcp_server=$(uci_get_by_name $GLOBAL_SERVER server)
		local kcp_port=$(uci_get_by_name $GLOBAL_SERVER kcp_port)
		local server_port=$(uci_get_by_name $GLOBAL_SERVER server_port)
		local password=$(uci_get_by_name $GLOBAL_SERVER kcp_password)
		local kcp_param=$(uci_get_by_name $GLOBAL_SERVER kcp_param)
		[ "$password" != "" ] && password="--key "$password
		service_start /usr/bin/kcptun-client -r $kcp_server:$kcp_port -l :$server_port $password $kcp_param
		kcp_enable_flag=1
		ARG_UDP=""
	fi
	if [ "$_local" == "1" ]; then
		local socks_port=$(uci_get_by_type socks5_proxy local_port)
		tcp_config_file=$TMP_PATH/local-ssr-retcp.json
		[ "$mode" == "tcp,udp" ] && tcp_config_file=$TMP_PATH/local-udp-ssr-retcp.json
	fi
	local tcp_port=$(uci_get_by_name $GLOBAL_SERVER local_port)
	local type=$(uci_get_by_name $GLOBAL_SERVER type)
	local has_ss_type=$(uci_get_by_type server_subscribe ss_type)
	case "$type" in
	ss | ssr)
		gen_config_file $GLOBAL_SERVER $type 1 $tcp_port
		if [ "$has_ss_type" = "ss-libev" -o "$type" = "ssr" ]; then
			ss_program="$(first_type ${type}-redir)"
		elif [ "$has_ss_type" = "ss-rust" ]; then
			ss_program="$(first_type ${type}local)"
		fi
		echolog "$(get_name $type) program is: $ss_program"
		# 获取当前软链接指向的执行文件路径
		old_ss_program=$(readlink -f "$TMP_PATH/bin/${type}-redir" 2>/dev/null)
		# **当新旧执行文件路径不同时，删除旧链接**
		if [ "$old_ss_program" != "$ss_program" ]; then
			rm -rf "$TMP_PATH/bin/${type}-redir"
		fi
		for i in $(seq 1 $threads); do
			ln_start_bin $ss_program ${type}-redir -c $tcp_config_file
		done
		echolog "Main node:$(get_name $type) $threads Threads Started!"
		;;
	v2ray)
		gen_config_file $GLOBAL_SERVER $type 1 $tcp_port $socks_port
		ln_start_bin $(first_type xray v2ray) v2ray run -c $tcp_config_file
		echolog "Main node:$($(first_type xray v2ray) version | head -1) Started!"
		;;
	trojan)
		gen_config_file $GLOBAL_SERVER $type 1 $tcp_port
		for i in $(seq 1 $threads); do
			ln_start_bin $(first_type $type) $type --config $tcp_config_file
		done
		echolog "Main node:$($(first_type $type) --version 2>&1 | head -1) , $threads Threads Started!"
		;;
	naiveproxy)
		gen_config_file $GLOBAL_SERVER $type 1 $tcp_port
		ln_start_bin $(first_type naive) naive $tcp_config_file
		echolog "Main node:$($(first_type naive) --version 2>&1 | head -1) , $threads Threads Started!"
		;;
	hysteria2)
		gen_config_file $GLOBAL_SERVER $type 1 $tcp_port $socks_port
		ln_start_bin $(first_type hysteria) hysteria client --config $tcp_config_file
		echolog "Main node:$($(first_type hysteria) version | grep Version | awk '{print "Hysteria2: " $2}') Started!"
		;;
	tuic)
		local PARAM
		[ $mode == "tcp" ] && PARAM="-T" || PARAM=""
		gen_config_file $GLOBAL_SERVER $type 1 $tmp_tcp_local_port
		ln_start_bin $(first_type tuic-client) tuic-client --config $tcp_config_file
		ln_start_bin $(first_type ipt2socks) ipt2socks "$PARAM" -R -b 0.0.0.0 -4 -s 127.0.0.1 -p $tmp_tcp_local_port -l $tcp_port
		if [ -n $socks_port ] && [ $GLOBAL_SERVER == $LOCAL_SERVER ]; then #start a new tuic instance
			gen_config_file $GLOBAL_SERVER $type 4 $socks_port
			ln_start_bin $(first_type tuic-client) tuic-client --config $local_config_file
			echolog "Global Socks5:tuic-client $($(first_type tuic-client) --version) Started!"
		fi
		echolog "Main node:tuic-client $($(first_type tuic-client) --version) Started!"
		;;
	shadowtls)
		if [ -z "$socks_port" ]; then
			gen_config_file $GLOBAL_SERVER $type 1 "10${tmp_tcp_local_port}"
			gen_config_file $GLOBAL_SERVER $type 1 "10${tmp_tcp_local_port}" 0 chain
		else
			gen_config_file $GLOBAL_SERVER $type 1 "10${tmp_tcp_local_port}"
			gen_config_file $GLOBAL_SERVER $type 1 "10${tmp_tcp_local_port}" $socks_port chain
		fi
		local chain_type=$(uci_get_by_name $GLOBAL_SERVER chain_type)
		case ${chain_type} in
		vmess)
			ln_start_bin $(first_type shadow-tls) shadow-tls config --config $chain_config_file
			ln_start_bin $(first_type xray v2ray) v2ray run -c $tcp_config_file
			echolog "Mian node:shadow-tls chain-to $($(first_type xray) --version) Started!"
			;;
		sslocal)
			ln_start_bin $(first_type shadow-tls) shadow-tls config --config $chain_config_file
			ln_start_bin $(first_type sslocal) sslocal -c $tcp_config_file
			echolog "Main node:shadow-tls chain-to $($(first_type sslocal) --version) Started!"
			;;
		esac
		;;
	socks5)
		if [ "$(uci_get_by_name $GLOBAL_SERVER auth_enable 0)" == "1" ]; then
			local auth="-a $(uci_get_by_name $GLOBAL_SERVER username) -k $(uci_get_by_name $GLOBAL_SERVER password)"
		fi
		ln_start_bin $(first_type ipt2socks) ipt2socks $tcp_config_file -R -4 -j $threads -s $(uci_get_by_name $GLOBAL_SERVER server) -p $(uci_get_by_name $GLOBAL_SERVER server_port) -l $tcp_port $auth
		#gen_config_file $GLOBAL_SERVER $type 1 $tcp_port
		#for i in $(seq 1 $threads); do
		#	ln_start_bin $(first_type redsocks2) redsocks2 -c $tcp_config_file
		#done
		echolog "Main node:Socks5 REDIRECT/TPROXY $threads Threads Started!"
		;;
	tun)
		gen_config_file $GLOBAL_SERVER $type 1 $tcp_port
		for i in $(seq 1 $threads); do
			ln_start_bin $(first_type redsocks2) redsocks2 -c $tcp_config_file
		done
		echolog "Main node:Network Tunnel REDIRECT $threads Threads Started!"
		;;
	esac
	redir_tcp=1
	return 0
}

load_config() {
	if [ -z "$switch_server" ]; then
		GLOBAL_SERVER=$(uci_get_by_type global global_server nil)
	else
		GLOBAL_SERVER=$switch_server
	fi
	if [ "$(uci_get_by_type socks5_proxy enabled 0)" == "1" ]; then
		# 只有开启 全局socks 才需要取值
		LOCAL_SERVER=$(uci_get_by_type socks5_proxy server nil)
	else
		# 没有开启 设置为 nil
		LOCAL_SERVER=nil
	fi
	if [ "$GLOBAL_SERVER" == "nil" ]; then
		mode="tcp,udp"
		_local="2"
		local_config_file=$TMP_PATH/tcp-udp-ssr-local.json
		start_local
		return 1
	fi
	UDP_RELAY_SERVER=$(uci_get_by_type global udp_relay_server nil)
	if [ "$(uci_get_by_type global netflix_enable 0)" == "1" ]; then
		# 只有开启 NetFlix分流 才需要取值
		SHUNT_SERVER=$(uci_get_by_type global netflix_server nil)
	else
		# 没有开启 设置为 nil
		SHUNT_SERVER=nil
	fi
	tcp_config_file=$TMP_PATH/tcp-only-ssr-retcp.json
	case "$UDP_RELAY_SERVER" in
	nil)
		if command -v nft >/dev/null 2>&1; then
			# nftables / fw4
			mode="tcp,udp"
			ARG_UDP=""
			udp_config_file=""
			UDP_RELAY_SERVER="nil"
			tcp_config_file=$TMP_PATH/nft-ssr-retcp.json
		else
			# iptables / fw3
			mode="tcp"
		fi
		;;
	$GLOBAL_SERVER | same)
		mode="tcp,udp"
		tcp_config_file=$TMP_PATH/tcp-udp-ssr-retcp.json
		ARG_UDP="-u"
		UDP_RELAY_SERVER=$GLOBAL_SERVER
		;;
	*)
		mode="udp"
		udp_config_file=$TMP_PATH/udp-only-ssr-reudp.json
		ARG_UDP="-U"
		start_udp
		if command -v nft >/dev/null 2>&1; then
			# nftables / fw4
			mode="tcp,udp"
		else
			# iptables / fw3
			mode="tcp"
		fi
		;;
	esac
	case "$LOCAL_SERVER" in
	nil)
		_local="0"
		;;
	$GLOBAL_SERVER | same)
		_local="1"
		LOCAL_SERVER=$GLOBAL_SERVER
		local_config_file=$TMP_PATH/tcp-udp-ssr-local.json
		start_local
		local_enable=0
		;;
	$SHUNT_SERVER)
		_local="3"
		local_config_file=$TMP_PATH/tcp-udp-ssr-local.json
		start_local
		;;
	*)
		_local="2"
		local_config_file=$TMP_PATH/tcp-udp-ssr-local.json
		start_local
		;;
	esac
	case "$SHUNT_SERVER" in
	nil)
		shunt="0"
		;;
	$GLOBAL_SERVER | same)
		shunt="1"
		SHUNT_SERVER=$GLOBAL_SERVER
		;;
	$LOCAL_SERVER)
		shunt="$tmp_shunt_port"
		shunt_config_file=$TMP_PATH/tcp-udp-ssr-local.json
		shunt_dns_config_file=$TMP_PATH/shunt-dns-ssr-plus.json
		start_shunt
		;;
	*)
		shunt="$tmp_shunt_port"
		shunt_config_file=$TMP_PATH/shunt-ssr-retcp.json
		shunt_dns_config_file=$TMP_PATH/shunt-dns-ssr-plus.json
		start_shunt
		;;
	esac
	return 0
}

check_server() {
	ENABLE_SERVER=$(uci_get_by_type global global_server nil)
	if [ "$ENABLE_SERVER" == "nil" ]; then
		return 1
	else
		local STYPE=$(uci_get_by_name $ENABLE_SERVER type nil)
		if [ "$STYPE" == "nil" ]; then
			local CFGID=$(uci_get_by_cfgid servers type nil)
			if [ "$CFGID" == "nil" ]; then
				uci_set_by_type global global_server 'nil'
			else
				uci_set_by_type global global_server $CFGID
			fi
			/etc/init.d/shadowsocksr restart
		fi
	fi
}

start_server() {
	[ "$(uci_get_by_type server_global enable_server 0)" == "0" ] && return 0
	server_service() {
		[ "$(uci_get_by_name $1 enable 0)" == "0" ] && return 1
		let server_count=server_count+1
		if [ "$server_count" == "1" ]; then
			if command -v nft >/dev/null 2>&1; then
				# nftables / fw4
				if nft list table inet fw4 >/dev/null 2>&1; then
					if ! nft list chain inet fw4 SSR-SERVER-RULE >/dev/null 2>&1; then
						nft add chain inet fw4 SSR-SERVER-RULE 2>/dev/null
					fi
					if ! nft list chain inet fw4 input 2>/dev/null | grep -q "jump SSR-SERVER-RULE"; then
						nft insert rule inet fw4 input jump SSR-SERVER-RULE comment \"SSR Server Input Hook\" 2>/dev/null
					fi
					nft flush chain inet fw4 SSR-SERVER-RULE 2>/dev/null
				fi
			else
				# iptables / fw3
				if ! (iptables-save -t filter | grep -q "SSR-SERVER-RULE"); then
					iptables -N SSR-SERVER-RULE
					iptables -t filter -I INPUT -j SSR-SERVER-RULE
				fi
			fi
		fi
		local type=$(uci_get_by_name $1 type)
		local has_ss_type=$(uci_get_by_type server_subscribe ss_type)
		case "$type" in
		ss | ssr)
			gen_service_file ${type} $1 $TMP_PATH/ssr-server$server_count.json
			if [ "$has_ss_type" = "ss-libev" -o "$type" = "ssr" ]; then
				ss_program="$(first_type ${type}-server)"
			elif [ "$has_ss_type" = "ss-rust" ]; then
				ss_program="$(first_type ${type}server)"
			fi
			# 获取当前软链接指向的执行文件路径
			old_ss_program=$(readlink -f "$TMP_PATH/bin/${type}-server" 2>/dev/null)
			# **当新旧执行文件路径不同时，删除旧链接**
			if [ "$old_ss_program" != "$ss_program" ]; then
				rm -rf "$TMP_PATH/bin/${type}-server" 
			fi
			ln_start_bin $ss_program ${type}-server -c $TMP_PATH/ssr-server$server_count.json
			echolog "Server: $(get_name ${type}) Server$server_count Started!"
			;;
		socks5)
			[ -e /proc/sys/net/ipv6 ] && local listenip='-i ::'
			ln_start_bin $(first_type microsocks) microsocks $listenip -p $(uci_get_by_name $1 server_port) -1 -u $(uci_get_by_name $1 username) -P $(uci_get_by_name $1 password) ssr-server$server_count
			echolog "Server:Socks5 Server$server_count Started!"
			;;
		esac
		server_port=$(uci_get_by_name $1 server_port)
		if command -v nft >/dev/null 2>&1; then
			# nftables / fw4
			nft add rule inet fw4 SSR-SERVER-RULE tcp dport $server_port accept
			nft add rule inet fw4 SSR-SERVER-RULE udp dport $server_port accept
		else
			# iptables / fw3
			iptables -t filter -A SSR-SERVER-RULE -p tcp --dport $server_port -j ACCEPT
			iptables -t filter -A SSR-SERVER-RULE -p udp --dport $server_port -j ACCEPT
		fi
		return 0
	}
	gen_serv_include() {
		local FWI=$(uci get firewall.shadowsocksr.path 2>/dev/null)
		[ -n "$FWI" ] || return 0
		if [ ! -f $FWI ]; then
			echo '#!/bin/sh' >$FWI
		fi
		if command -v nft >/dev/null 2>&1; then
			# nftables / fw4
			cat <<-'EOF' >>"$FWI"
				# 确保表存在
				if nft list table inet fw4 >/dev/null 2>&1; then
					# 如果不存在 SSR-SERVER-RULE 链，则创建
					if ! nft list chain inet fw4 SSR-SERVER-RULE >/dev/null 2>&1; then
						nft add chain inet fw4 SSR-SERVER-RULE 2>/dev/null
					# 从 input 链跳转到 SSR-SERVER-RULE（如果未添加）
					if ! nft list chain inet fw4 input | grep -q 'jump SSR-SERVER-RULE'; then
						nft insert rule inet fw4 input jump SSR-SERVER-RULE comment \"SSR Server Input Hook\" 2>/dev/null
					fi
					# 已存在则清空链
					nft flush chain inet fw4 SSR-SERVER-RULE 2>/dev/null
				fi
			EOF
		else
			# iptables / fw3
			extract_rules() {
				echo "*filter"
				iptables-save -t filter | grep SSR-SERVER-RULE | sed -e "s/^-A INPUT/-I INPUT/"
				echo 'COMMIT'
			}
			cat <<-EOF >>$FWI
				iptables-save -c | grep -v "SSR-SERVER" | iptables-restore -c
				iptables-restore -n <<-EOT
				$(extract_rules)
				EOT
			EOF
		fi
	}

	config_load $NAME
	config_foreach server_service server_config
	gen_serv_include
	return 0
}

start_switch() {
	if [ "$(uci_get_by_type global enable_switch 0)" == "1" ]; then
		if [ -z "$switch_server" ]; then
			local switch_time=$(uci_get_by_type global switch_time)s
			local switch_timeout=$(uci_get_by_type global switch_timeout)
			service_start /usr/bin/ssr-switch start $switch_time $switch_timeout
		fi
	fi
}

start_monitor() {
	if [ $(uci_get_by_type global monitor_enable 1) == "1" ]; then
		let total_count=server_count+redir_tcp+redir_udp+kcp_enable_flag+local_enable+pdnsd_enable_flag
		if [ $total_count -gt 0 ]; then
			service_start /usr/bin/ssr-monitor $server_count $redir_tcp $redir_udp $kcp_enable_flag $local_enable $pdnsd_enable_flag
		fi
	fi
}

start_rules() {
	local server=$(get_host_ip $GLOBAL_SERVER)
	local local_port=$(uci_get_by_name $GLOBAL_SERVER local_port)
	local lan_ac_ips=$(uci_get_by_type access_control lan_ac_ips)
	local lan_ac_mode=$(uci_get_by_type access_control lan_ac_mode)
	if [ "$kcp_enable_flag" == "0" -a "$redir_udp" == "1" ]; then
		local udp_server=$(get_host_ip $UDP_RELAY_SERVER)
		local udp_local_port=$tmp_udp_port
	fi
	if [ "$shunt" != "0" ]; then
		local shunt_ip=$(get_host_ip $SHUNT_SERVER)
	fi
	if [ -n "$lan_ac_ips" ]; then
		case "$lan_ac_mode" in
		w | W | b | B) local ac_ips="$lan_ac_mode$lan_ac_ips" ;;
		esac
	fi
	gfwmode() {
		case "$(uci_get_by_type global run_mode)" in
		gfw) echo "-g" ;;
		router) echo "-r" ;;
		oversea) echo "-c" ;;
		all) echo "-z" ;;
		esac
	}
	if [ "$(uci_get_by_type global dports)" == "3" ]; then
		local custom_ports=$(uci_get_by_name $GLOBAL_SERVER custom_ports)  #  custom_ports 存储了用户自定义的端口
		if [ -n "$custom_ports" ]; then
			local proxyport="-m multiport --dports $custom_ports"
		fi
	else
		if [ "$(uci_get_by_type global dports 1)" == "2" ]; then
			local proxyport="-m multiport --dports 22,53,587,465,995,993,143,80,443,853,9418"
		fi
	fi

	get_arg_out() {
		case "$(uci_get_by_type access_control router_proxy 1)" in
		1) echo "-o" ;;
		2) echo "-O" ;;
		esac
	}
	if command -v nft >/dev/null 2>&1; then
		ARG_A="-A"
	else
		ARG_A=""
	fi
	/usr/share/shadowsocksr/gfw2ipset.sh
	/usr/bin/ssr-rules \
		-s "$server" \
		-l "$local_port" \
		-S "$udp_server" \
		-L "$udp_local_port" \
		-a "$ac_ips" \
		-i "/etc/ssrplus/china_ssr.txt" \
		-b "$(uci_get_by_type access_control wan_bp_ips)" \
		-w "$(uci_get_by_type access_control wan_fw_ips)" \
		-B "$(uci_get_by_type access_control lan_bp_ips)" \
		-p "$(uci_get_by_type access_control lan_fp_ips)" \
		-G "$(uci_get_by_type access_control lan_gm_ips)" \
		-m "$(uci_get_by_type access_control Interface)" \
		-D "$proxyport" \
		-F "$shunt" \
		-N "$shunt_ip" \
		-M "$(uci_get_by_type global netflix_proxy 0)" \
		-I "/etc/ssrplus/netflixip.list" \
		$(get_arg_out) $(gfwmode) $ARG_UDP $ARG_A
		
	return $?
}

start() {
	set_lock
	echolog "----------start------------"
	mkdir -p /var/run /var/lock /var/log $DNSMASQ_CONF_DIR $TMP_BIN_PATH $TMP_DNSMASQ_PATH
	echo "conf-dir=${TMP_DNSMASQ_PATH}" >"$DNSMASQ_CONF_DIR/dnsmasq-ssrplus.conf"
	if load_config; then
		Start_Run
		start_rules
		start_dns
		add_cron
		start_switch
	else
		echolog "未启动主节点，禁止连接的域名正在加载。"
		cat /etc/ssrplus/deny.list | sed '/^$/d' | sed '/#/d' | sed "/.*/s/.*/address=\/&\//" >$TMP_DNSMASQ_PATH/denylist.conf
		echolog "禁止连接的域名加载完毕。"
		if [ "$(uci_get_by_type global adblock 0)" == "1" ]; then
			echolog "未启动主节点，广告过滤正在加载。"
			cp -f /etc/ssrplus/ad.conf $TMP_DNSMASQ_PATH/
			if [ -f "$TMP_DNSMASQ_PATH/ad.conf" ]; then
				for line in $(cat /etc/ssrplus/black.list); do sed -i "/$line/d" $TMP_DNSMASQ_PATH/ad.conf; done
				for line in $(cat /etc/ssrplus/white.list); do sed -i "/$line/d" $TMP_DNSMASQ_PATH/ad.conf; done
				for line in $(cat /etc/ssrplus/deny.list); do sed -i "/$line/d" $TMP_DNSMASQ_PATH/ad.conf; done
			fi
			echolog "广告过滤加载完毕。"
		fi
	fi
	/etc/init.d/dnsmasq restart >/dev/null 2>&1
	check_server
	start_server
	start_monitor
	clean_log
	echolog "-----------end------------"
	unset_lock
}

boot() {
	echolog "boot！"
	mkdir -p /var/run /var/lock /var/log $DNSMASQ_CONF_DIR $TMP_BIN_PATH $TMP_DNSMASQ_PATH
	start
}

stop() {
	unlock
	set_lock
	if command -v nft >/dev/null 2>&1; then
		/usr/bin/ssr-rules -K
		#local CLEANUP_PERSISTENCE="$(uci_get_by_type global global_server nil)"
		#if [ "$CLEANUP_PERSISTENCE" == "nil" ]; then
		#	/usr/bin/ssr-rules -X
		#fi
	fi
	/usr/bin/ssr-rules -f
	local srulecount=0
	if command -v nft >/dev/null 2>&1; then
		# nftables / fw4
		#local srulecount=$(nft list ruleset 2>/dev/null | grep -c 'SSR-SERVER-RULE')
		if nft list chain inet fw4 SSR-SERVER-RULE >/dev/null 2>&1; then
			srulecount=$(nft list chain inet fw4 SSR-SERVER-RULE | grep SSR-SERVER-RULE | wc -l)
		fi
	else
		# iptables / fw3
		srulecount=$(iptables -L | grep SSR-SERVER-RULE | wc -l)
	fi
	if [ $srulecount -gt 0 ]; then
		if command -v nft >/dev/null 2>&1; then
			# nftables / fw4
			if nft list table inet fw4 >/dev/null 2>&1; then
				if nft list chain inet fw4 SSR-SERVER-RULE >/dev/null 2>&1; then
					for handle in $(nft --handle list chain inet fw4 input 2>/dev/null | \
						grep 'jump SSR-SERVER-RULE' | awk '{for(i=1;i<=NF;i++) if($i=="handle") print $(i+1)}'); do
						nft delete rule inet fw4 input handle $handle 2>/dev/null || true
					done
					nft flush chain inet fw4 SSR-SERVER-RULE 2>/dev/null || true
					nft delete chain inet fw4 SSR-SERVER-RULE 2>/dev/null || true
				fi
			fi
		else
			# iptables / fw3
			if iptables-save -t filter | grep -q "SSR-SERVER-RULE"; then
				logger -t ssr-rules "Flushing and deleting SSR-SERVER-RULE chain (iptables)"
				iptables -F SSR-SERVER-RULE 2>/dev/null || true
				iptables -t filter -D INPUT -j SSR-SERVER-RULE 2>/dev/null || true
				iptables -X SSR-SERVER-RULE 2>/dev/null || true
			fi
		fi
	fi
	if [ -z "$switch_server" ]; then
		$PS -w | grep -v "grep" | grep ssr-switch | awk '{print $1}' | xargs kill -9 >/dev/null 2>&1 &
		rm -f /var/lock/ssr-switch.lock
		killall -q -9 kcptun-client
	fi
	$PS -w | grep -v "grep" | grep ssr-monitor | awk '{print $1}' | xargs kill -9 >/dev/null 2>&1 &
	$PS -w | grep -v "grep" | grep ssr-rules | awk '{print $1}' | xargs kill -9 >/dev/null 2>&1 &
	$PS -w | grep -v "grep" | grep "sleep 0000" | awk '{print $1}' | xargs kill -9 >/dev/null 2>&1 &
	( \
		# Graceful kill first, so programs have the chance to stop its subprocesses
		$PS -w | grep -v "grep" | grep "$TMP_PATH" | awk '{print $1}' | xargs kill >/dev/null 2>&1 ; \
		sleep 3s; \
		# Force kill hanged programs
		$PS -w | grep -v "grep" | grep "$TMP_PATH" | awk '{print $1}' | xargs kill -9 >/dev/null 2>&1 ; \
	)
	killall -q -9 v2ray-plugin obfs-local xray-plugin shadow-tls
	rm -f /var/lock/ssr-monitor.lock
	if [ "$(uci -q get "dhcp.@dnsmasq[0]._unused_ssrp_changed")" = "1" ]; then
		uci -q del "dhcp.@dnsmasq[0].noresolv"
		uci -q del_list "dhcp.@dnsmasq[0].server"="127.0.0.1#$china_dns_port"
		uci -q rename "dhcp.@dnsmasq[0]._orig_noresolv"="noresolv"
		uci -q rename "dhcp.@dnsmasq[0]._orig_server"="server"
		uci -q del "dhcp.@dnsmasq[0]._unused_ssrp_changed"
		uci -q commit "dhcp"
	fi
	if [ -f "$DNSMASQ_CONF_DIR/dnsmasq-ssrplus.conf" ]; then
		rm -rf $DNSMASQ_CONF_DIR/dnsmasq-ssrplus.conf \
			$TMP_DNSMASQ_PATH \
			$TMP_PATH/*-ssr-*.json \
			$TMP_PATH/ssr-server*.json \
			$TMP_PATH/*-config-*.json

		/etc/init.d/dnsmasq restart >/dev/null 2>&1
	fi
	del_cron
	unset_lock
}

reset() {
	stop
	set_lock
	rm -rf /etc/config/shadowsocksr $LOG_FILE
	touch /etc/config/shadowsocksr $LOG_FILE
	cp /usr/share/shadowsocksr/shadowsocksr.config /etc/config/shadowsocksr
	unset_lock
}
